
package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/*"}, initParams = {@WebInitParam(name = "whites", value = "register.jsp,/login,login.jsp,.js,.css")})
public class LoginFilter implements Filter {
    String[] whites;

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        Boolean sessionObj = Boolean.valueOf(false);
        for (String s : this.whites) {
            if (request.getRequestURI().endsWith(s)) {
                sessionObj = Boolean.valueOf(true);

                break;

            }

        }
        if (sessionObj.booleanValue()) {

            chain.doFilter(req, resp);

        } else {

            HttpSession session = request.getSession();

            Object obj = session.getAttribute("user");

            System.out.println(obj);

            if (obj == null) {

                response.sendRedirect("/userinfo/html/login.jsp");

                chain.doFilter(req, resp);

            } else {

                chain.doFilter(req, resp);

            }

        }

    }


    public void destroy() {
    }


    public void init(FilterConfig config) throws ServletException {

        this.whites = config.getInitParameter("whites").split(",");

    }

}
